package com.todo.auth.service;

import com.todo.admin.common.base.SystemLoginUser;
import com.todo.auth.remote.StaffRemoteService;
import com.todo.auth.remote.dto.StaffDetailDTO;
import com.todo.auth.remote.dto.StaffUserNameDTO;
import com.todo.auth.tool.TokenService;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 自定义加载用户信息通过用户名
 * 用于SpringSecurity 登录流程
 * 没有办法把这个类 放进loginService中  会在SecurityConfig中造成循环依赖
 *
 * @author azhebuxing
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class StaffDetailsServiceImpl implements UserDetailsService {

    @Resource
    private StaffRemoteService staffRemoteService;
    @Resource
    private TokenService tokenService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        StaffUserNameDTO staffUserNameDTO = new StaffUserNameDTO();
        staffUserNameDTO.setUsername(username);
        BizResponse<StaffDetailDTO> bizResponse = staffRemoteService.queryStaffDetailByUserName(staffUserNameDTO);
        if (bizResponse == null || bizResponse.getData() == null) {
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        StaffDetailDTO staffDetailDTO = bizResponse.getData();
        SystemLoginUser loginUser = new SystemLoginUser(staffDetailDTO.getUserId(), staffDetailDTO.isAdmin(), staffDetailDTO.getUsername(),
                staffDetailDTO.getPassword(), staffDetailDTO.getRoleInfo(), staffDetailDTO.getDeptId());
        loginUser.fillLoginInfo();
        loginUser.setAutoRefreshCacheTime(loginUser.getLoginInfo().getLoginTime()
                + TimeUnit.MINUTES.toMillis(tokenService.getAutoRefreshTime()));
        return loginUser;

    }


}
